<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-form ref="lottery" :model="lotteryForm" label-width="80px">
      <el-form-item>-->
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <!-- </el-form-item>
      </el-form>-->
    </div>
    <el-table :data="lotteryData" border style="width: 100%">
      <el-table-column type="selection" />
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="strLotteryname" label="抽奖活动名称" min-width="110" />
      <el-table-column prop="iLotterynum" label="编号" min-width="110" />
      <el-table-column prop="strDetail" label="抽奖活动说明" min-width="110" />
      <el-table-column prop="iLotterystatus" label="抽奖活动状态" min-width="110">
        <template slot-scope="{row}">{{ row.iLotterystatus===1?"开启":"关闭" }}</template>
      </el-table-column>
      <el-table-column prop="strStarttime" label="开始时间" min-width="110" />
      <el-table-column prop="strEndtime" label="结束时间" min-width="110" />
      <!-- <el-table-column prop="iLevel" label="奖项等级" />
      <el-table-column prop="iQuantity" label="奖项数量" />-->
      <el-table-column prop="strOperatorname" label="操作者" min-width="110" />
      <el-table-column label="操作" width="180">
        <template slot-scope="{row}">
          <!-- <template v-if="row.iOrgsysnum === iOrgsysnum || iOrgsysnum === -1"> -->
          <el-button size="mini" type="primary" @click="handleModify(row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
          <!-- </template>
          <template v-else>/</template>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pagenum"
      :limit.sync="limit"
      :layout="layout"
      @pagination="getData"
    />
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      min-width="50%"
      :close-on-click-modal="false"
    >
      <div>
        <el-form ref="dialogForm" :model="dialogForm" :rules="dialogRules" label-width="110px">
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="抽奖活动名称" prop="strLotteryname">
                <el-input v-model="dialogForm.strLotteryname" placeholder="请输入抽奖活动名称" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="创建者" prop="strOperator">
                <el-input v-model="dialogForm.strOperator" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="抽奖活动说明" prop="strDetail">
                <el-input v-model="dialogForm.strDetail" type="textarea" placeholder="请输入抽奖活动说明" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="抽奖活动状态" prop="iLotterystatus">
                <el-select v-model="dialogForm.iLotterystatus" placeholder="请选择抽奖活动状态">
                  <el-option
                    v-for="item in actOpts"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="所属机构" prop="iOrgsysnum">
                <el-cascader
                  v-model="dialogForm.iOrgsysnum"
                  :show-all-levels="false"
                  :options="options"
                  :props="{ expandTrigger: 'hover', value:'strOrgnum',label:'strOrgname',children: 'yhlist' ,checkStrictly: true }"
                />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :xs="24">
              <el-form-item label="开始时间" prop="strStarttime">
                <el-date-picker
                  v-model="dialogForm.strStarttime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择开始时间"
                  :picker-options="expireTimeOption"
                />
              </el-form-item>
            </el-col>

            <el-col :sm="12" :xs="24">
              <el-form-item label="结束时间" prop="strEndtime">
                <el-date-picker
                  v-model="dialogForm.strEndtime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择结束时间"
                  :picker-options="expireTimeOption2"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="awardsInfo" label="奖项列表">
                <el-button
                  type="primary"
                  size="mini"
                  style="margin-bottom: 16px"
                  @click="addAward"
                >添加奖项</el-button>
                <el-table
                  ref="awaraTable"
                  v-loading="loading"
                  :data="awardsInfo"
                  style="width: 100%"
                  border
                >
                  <el-table-column type="index" width="55" label="序号" />
                  <el-table-column prop="strAwardname" label="奖项名称" />
                  <el-table-column prop="iQuantity" label="奖项数量" />
                  <el-table-column prop="strImg" label="图片" width="100px">
                    <template slot-scope="{row}">
                      <el-image style="width: 100px; height: 100px" :src="row.strImg" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="iLevel" label="奖项等级">
                    <template slot-scope="{row}">{{ row.iLevel | levelMap }}</template>
                  </el-table-column>
                  <el-table-column label="操作" min-width="180">
                    <template slot-scope="{row, $index}">
                      <el-button size="mini" type="danger" @click="awardlistdele(row, $index)">移除</el-button>
                      <el-button size="mini" type="primary" @click="handleEdit(row, $index)">编辑</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="cancelDgClearForm('dialogForm')">取 消</el-button>
        <el-button v-if="dialogTitle === optsTitle.add" type="primary" @click="addSubmit">确 定</el-button>
        <el-button v-else type="primary" @click="editRow">修 改</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="awardDiaTle" :visible.sync="dialogOthers" width="50%">
      <el-form ref="form" :rules="rulesForm" :model="form" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="奖项名称" prop="strAwardname">
              <el-input v-model.number="form.strAwardname" class="inptw200" placeholder="奖项名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="奖项等级" prop="iLevel">
              <el-select v-model="form.iLevel" placeholder="请选择奖项等级">
                <el-option
                  v-for="item in levelOpts"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="奖项数量" prop="iQuantity">
              <el-input v-model.number="form.iQuantity" class="inptw200" placeholder="奖项数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="strImg" label="奖品图片">
              <el-upload
                class="avatar-uploader"
                :action="baseImgRUL"
                name="uploadFile"
                :show-file-list="false"
                :on-success="(response, file)=>{handleSuccess(response, file, 'form', 'strImg'),$refs['form'].clearValidate('strImg')}"
                :before-upload="beforeUpload"
                :on-progress="uploadImageProcess"
              >
                <el-progress
                  v-if="imageFlag == true"
                  type="circle"
                  :percentage="imageUploadPercent"
                  style="margin-top:30px;"
                />
                <template v-else>
                  <img v-if="form.strImg" :src="form.strImg" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogOthers = false">取 消</el-button>
        <el-button v-if="awardDiaTle === awardTitle.add" type="primary" @click="pushlotter">确 定</el-button>
        <el-button v-else type="primary" @click="editlotter">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  addRowData,
  updataRow,
  deleteRow,
  getAwardlist
} from '@/api/lottery'
import mixins from '@/mixins/uploadImg'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'
import { getOrglists } from '../../api/addTag'
import { getSysType, getParentNumArr } from '../../api/common'
// import { SingleImageUpload } from '@/components/Upload/SingleImage'

const mapObj = {}

export default {
  name: 'Lottery',
  components: {
    Pagination
    // SingleImageUpload
  },
  filters: {
    levelMap(val) {
      return mapObj[parseInt(val)]
    }
  },
  mixins: [mixins],
  data() {
    var valdateiQuantity = (rule, value, callback) => {
      const reg = /^[1-9]/
      if (value === '') {
        callback(new Error('不能为空'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字'))
      } else {
        callback()
      }
    }
    var valdateName = (rule, value, callback) => {
      // 用户名正则，4到16位（字母，数字，下划线，减号）
      const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]{1,16}$/
      if (value === '') {
        callback(new Error('抽奖名称不能为空哦'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入1-25位汉字、字母、数字'))
      } else {
        callback()
      }
    }
    var valdateTextarea = (rule, value, callback) => {
      // 用户名正则，4到16位（字母，数字，下划线，减号）\u3002 。 \uff0c,
      const reg = /^[\u4e00-\u9fa5a-zA-Z0-9\uff0c\u3002]{1,200}$/
      if (!reg.test(value)) {
        callback(new Error('请输入1-25位汉字、字母、数字'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      dialogOthers: false,
      lotteryTile: '新增抽奖',
      optsTitle: {
        add: '新增抽奖',
        edit: '修改抽奖'
      },
      awardTitle: {
        add: '添加奖项',
        edit: '修改奖项'
      },
      awardDiaTle: '添加奖项',
      dialogTitle: '',
      total: 0,
      limit: 5,
      layout: 'total, prev, pager, next, jumper',
      actOpts: [
        {
          label: '关闭',
          value: '0'
        },
        {
          label: '开启',
          value: '1'
        }
      ],
      levelOpts: [],
      expireTimeOption: this.beginDate(),
      expireTimeOption2: this.processDate(),
      dialogForm: {
        strLotteryname: '',
        iLotterystatus: '',
        strDetail: '',
        strOperator: this.name,
        iOrgsysnum: [],
        strStarttime: '',
        strEndtime: '',
        awardsInfo: [] // 奖项列表
      },
      awardsInfo: [],
      form: {
        strAwardname: '',
        iLevel: '',
        iQuantity: '',
        strImg: ''
      },
      dialogRules: {
        strLotteryname: [
          { required: true, validator: valdateName, trigger: 'blur' }
        ],
        strDetail: [
          { required: true, message: '请输入抽奖活动说明', trigger: 'blur' },
          { validator: valdateTextarea }
        ],
        iOrgsysnum: [
          { required: true, message: '请选择机构类型', trigger: 'change' }
        ],

        strStarttime: [
          {
            required: true,
            message: '请选择开始时间',
            trigger: 'change'
          }
        ],
        strEndtime: [
          {
            required: true,
            message: '请选择结束时间',
            trigger: 'change'
          }
        ],
        iLotterystatus: [
          {
            required: true,
            message: '请选择抽奖活动状态',
            trigger: 'change'
          }
        ]
      },
      rulesForm: {
        strAwardname: [
          { required: true, validator: valdateName, trigger: 'blur' }
        ],
        strImg: [
          {
            required: true,
            message: '请上传奖品图片',
            trigger: 'change'
          }
        ],
        iLevel: [
          {
            required: true,
            message: '请选择奖项等级',
            trigger: 'change'
          }
        ],
        iQuantity: [
          {
            required: true,
            validator: valdateiQuantity,
            trigger: 'blur'
          }
        ]
      },
      options: [],
      lotteryData: [],
      lotteryForm: {},
      loading: false,
      sourceIndex: null, // 修改奖项获取的 awardsInfo 数组索引
      listQuery: {
        iOrgsysnum: '',
        pagenum: 1
      }
    }
  },
  computed: {
    ...mapGetters(['iOrgsysnum', 'name', 'userID'])
  },
  created() {
    this.getData()
    this.dialogTitle = this.optsTitle.add
    this.dialogForm.strOperator = this.name
    // 获取所属机构有权限

    getOrglists({ iOrgnum: this.iOrgsysnum }).then(res => {
      // console.log(res)
      if (res.data && Array.isArray(res.data)) {
        this.options = res.data
      } else {
        this.options.push(res.data)
      }
      // this.optionslist = res.data
    })

    getSysType({ typeInfo: ['12'] }).then(res => {
      const temp = []
      res.data[12].forEach(el => {
        temp.push({
          value: el.strCode,
          label: el.strValue
        })
        mapObj[el.strCode] = el.strValue
      })
      this.levelOpts = temp.reverse()
    })

    this.$nextTick(() => {
      this.dialogForm.iOrgsysnum.push(this.iOrgsysnum + '')
    })
  },
  methods: {
    getData() {
      this.listQuery.iOrgsysnum = this.iOrgsysnum
      fetchList(this.listQuery).then(res => {
        this.lotteryData = res && res.data
        this.total = res && res.total
      })
    },
    handleAdd() {
      /** 添加抽奖 */
      this.dialogVisible = true
      this.dialogTitle = this.optsTitle.add
      this.dialogForm = {
        strLotteryname: '',
        iLotterystatus: '',
        strDetail: '',
        strOperator: this.name,
        iOrgsysnum: '',
        strStarttime: '',
        strEndtime: '',
        awardsInfo: []
      }
      this.awardsInfo = []
      this.$nextTick(_ => {
        this.$refs['dialogForm'].clearValidate()
      })
    },
    addAward() {
      this.form = {
        strAwardname: '',
        iLevel: '',
        iQuantity: '',
        strImg: ''
      }
      this.awardDiaTle = this.awardTitle.add
      this.dialogOthers = true

      this.$nextTick(_ => this.$refs['form'].clearValidate())
    },
    pushlotter() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const ret = this.awardsInfo.find(
            item => item.iLevel === parseInt(this.form.iLevel)
          ) // 数组中不存在返回undefined

          if (ret) {
            this.$message.warning('已存在' + mapObj[this.form.iLevel])
            return false
          }
          this.awardsInfo.push(this.form)
          this.dialogOthers = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    cancelDgClearForm(formName) {
      this.$refs[formName].resetFields()
      this.dialogVisible = false
    },
    addSubmit() {
      this.$refs['dialogForm'].validate(valid => {
        if (valid) {
          console.log('object')
          const queryParams = this.dialogForm
          queryParams.awardsInfo = JSON.stringify(this.awardsInfo)
          queryParams.strOperator = this.userID

          addRowData(queryParams).then(res => {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            this.getData()
            this.dialogVisible = false
            this.$refs['dialogForm'].resetFields()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    editRow() {
      this.$refs['dialogForm'].validate(valid => {
        if (valid) {
          this.dialogForm.awardsInfo = JSON.stringify(this.awardsInfo)
          const queryParams = this.dialogForm
          queryParams.awardsInfo = JSON.stringify(this.awardsInfo)
          queryParams.strOperator = this.userID
          updataRow(queryParams).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.getData()
            this.dialogVisible = false
            this.$refs['dialogForm'].resetFields()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleModify(row) {
      getAwardlist({ iLotterynum: row.iLotterynum })
        .then(res => {
          this.awardsInfo = res.data === undefined ? [] : res.data
        })
        .catch(err => {
          console.log(err)
        })
      this.dialogTitle = this.optsTitle.edit
      this.dialogForm = row
      this.dialogForm = {
        strLotteryname: row.strLotteryname,
        iLotterystatus: row.iLotterystatus + '',
        strDetail: row.strDetail,
        strOperator: row.strOperatorname,
        iOrgsysnum: [],
        strStarttime: row.strStarttime,
        strEndtime: row.strEndtime,
        awardsInfo: []
      }
      getParentNumArr({ iOrgsysnum: row.iOrgsysnum }).then(res => {
        // if (res.data.indexOf(',') > 0) {
        this.dialogForm.iOrgsysnum = res.data.split(',')
        // } else {
        //   this.dialogForm.iOrgsysnum = res.data.split(',')
        // }
      })
      this.$nextTick(_ => {
        this.dialogVisible = true
      })
    },

    handleDelete(row) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        deleteRow({ idInfo: [row.id] }).then(res => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getData()
        })
      })
    },
    awardlistdele(row, index) {
      this.awardsInfo.splice(index)
    },
    handleEdit(row, index) {
      this.form = {
        strAwardname: row.strAwardname,
        iLevel: row.iLevel + '',
        iQuantity: row.iQuantity,
        strImg: row.strImg
      }
      this.dialogOthers = true
      this.awardDiaTle = this.awardTitle.edit
      this.sourceIndex = index
    },
    editlotter() {
      // vue--改变指定数组指定下标的值 并更新视图
      this.awardsInfo[this.sourceIndex] = this.form
      this.awardsInfo = Object.assign([], this.awardsInfo)
      this.dialogOthers = false
    },
    beginDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.dialogForm.strEndtime) {
            return new Date(self.dialogForm.strEndtime) < time
          } else {
            return time < Date.now() - 8.64e7
          }
        }
      }
    },
    processDate() {
      const self = this
      return {
        disabledDate(time) {
          if (self.dialogForm.strStarttime) {
            return new Date(self.dialogForm.strStarttime) > time
          } else {
            return time < Date.now() - 8.64e7
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
